package com.it.data_stack;

import java.util.Iterator;

/**
 * @author: Coke
 * @DateTime: 2023/06/11/20:39
 * 基于链表实现栈
 **/
public class LinkListStack<E> implements Stack<E>, Iterable<E> {
    
    private int capacity; // 节点数
    private int size; // 容量
    private Node<E> head = new Node<>(null, null);
    
    public LinkListStack (int capacity) {
        this.capacity = capacity;
    }
    
    @Override
    public boolean push (E val) {
        if (isFull()) {
            return false;
        }
        head.next = new Node<>(val, head.next);
        size++;
        return true;
    }
    
    @Override
    public E pop () {
        if (isEmpty()) {
            return null;
        }
        Node<E> next = head.next;
        head.next = next.next;
        size--;
        return next.val;
    }
    
    @Override
    public E peek () {
        if (isEmpty()) {
            return null;
        }
        return head.next.val;
    }
    
    @Override
    public boolean isEmpty () {
        return head.next == null;
    }
    
    @Override
    public boolean isFull () {
        return size == capacity;
    }
    
    @Override
    public Iterator<E> iterator () {
        return new Iterator<E>() {
            Node<E> p = head.next;
            
            @Override
            public boolean hasNext () {
                return p != null;
            }
            
            @Override
            public E next () {
                E val = p.val;
                p = p.next;
                return val;
            }
        };
    }
    
    static class Node<E> {
        E val;
        Node<E> next;
        
        public Node (E val, Node<E> next) {
            this.val = val;
            this.next = next;
        }
    }
    
}
